//创建用户相关
import { defineStore } from 'pinia'
import { reqLogin } from '@/api/user'
import { LoginFormData } from '@/api/user/types'

import { ElMessage as Message } from 'element-plus'
//引入常量路由，便于后期冬天生成路由
import { constantRoutes } from '@/router/router'
import { UserState } from './types/type'
let userStore = defineStore('User', {
  //存储数据
  state: (): UserState => {
    return {
      token: localStorage.getItem('token') || '', //用户登录成功后，后台返回的token,持久化存储
      menuRoutes: constantRoutes,
    }
  },
  //异步|处理逻辑
  actions: {
    async userLogin(form: LoginFormData) {
      try {
        let res = await reqLogin(form)
        console.log('登录结果111', res)
        //登录成功后，存储token
        if (res.code === 200) {
          //通过pinia存储token
          this.token = res.data.token
          //通过本地存储持久化token
          localStorage.setItem('token', res.data.token)
          Message.success('登录成功')

          return 1
        } else {
          //登陆失败
          Message.error('登录失败')
          console.log('登录失败')
          return Promise.reject(new Error(res.data.message))
        }
      } catch (error) {
        Message.error('登录成功')
        console.log('登录失败', error)
        return Promise.reject(new Error('登录失败'))
      }
    },
  },
  //计算属性
  getters: {},
})

export default userStore
